package mytomcat.servlet;

import com.alibaba.fastjson.JSON;
import mytomcat.MyTomcat;
import mytomcat.anno.Servlet;
import mytomcat.core.MyRequest;
import mytomcat.core.MyResponse;
import mytomcat.dto.ResultMessage;
import mytomcat.dto.ServletInfo;
import mytomcat.entity.TBlog;
import mytomcat.mapper.TBlogMapper;
import mytomcat.servlet.base.MyServlet;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author swc
 * @date 2020/6/2 0002 下午 16:13
 */
@Servlet(url="blog/list")
public class TBlogServelt extends MyServlet {

       private SqlSession sqlSession = MyTomcat.sqlSession;

        @Override
        public void doGet(MyRequest myRequest, MyResponse myResponse, ServletInfo servletInfo) {
            TBlogMapper tBlogMapper = sqlSession.getMapper(TBlogMapper.class);
            TBlog tBlog =new TBlog();
            tBlog.setContent(UUID.randomUUID().toString());
            tBlog.setTitle("内容是随机的"+System.currentTimeMillis());

            tBlogMapper.add(tBlog);
            sqlSession.commit();

            List<TBlog> tBlogs = tBlogMapper.selectList();

            ResultMessage resultMessage =new ResultMessage();
            resultMessage.setCode(200);
            resultMessage.setMessage("success");
            resultMessage.setRecodes(tBlogs);

            try {
                myResponse.writeJSon(JSON.toJSONString(resultMessage));
            }catch (IOException ex){
                ex.printStackTrace();
            }
        }

        public void doPost(MyRequest myRequest, MyResponse myResponse, ServletInfo servletInfo) {
            try {
                myResponse.write("欢迎来到 helloworld ....",null);
            }catch (IOException ex){
                ex.printStackTrace();
            }
        }
}
